import 'package:mobile_app.core/core/domain/entities/google_apple_store_api/purchase_item.dart';
import 'package:mobile_app.core/google_apple_store_purchases/domain/helpers/add_spaces_to_price/helper.dart';

const _kPrettifiablePriceCurrencies = {
  'RUB',
  'USD',
  'EUR',
  'KZT',
  'GBP',
  'CAD',
  'ILS',
};

abstract class GetGoogleAppleStoreApiPurchaseItemPrettifiedMonthlyPrice {
  String? call({
    required GoogleAppleStoreApiPurchaseItem storeApiPurchaseItem,
    required int months,
  });
}

class GetGoogleAppleStoreApiPurchaseItemPrettifiedMonthlyPriceImpl
    implements GetGoogleAppleStoreApiPurchaseItemPrettifiedMonthlyPrice {
  const GetGoogleAppleStoreApiPurchaseItemPrettifiedMonthlyPriceImpl({
    required AddSpacesToPrice addSpacesToPrice,
  }) : _addSpacesToPrice = addSpacesToPrice;

  final AddSpacesToPrice _addSpacesToPrice;

  @override
  String? call({
    required GoogleAppleStoreApiPurchaseItem storeApiPurchaseItem,
    required int months,
  }) {
    final prettifiablePriceRegExp = RegExp(r'^[0-9]+(\.[0-9]+)?$');
    final pricesPrettifiable = prettifiablePriceRegExp.hasMatch(storeApiPurchaseItem.price) &&
        _kPrettifiablePriceCurrencies.contains(storeApiPurchaseItem.currency);

    if (!pricesPrettifiable) {
      return null;
    }

    final monthlyPrice = _addSpacesToPrice(
      price: (double.parse(storeApiPurchaseItem.price) / months).toString(),
      delimiter: '.',
    );

    final monthlyPriceParts = monthlyPrice.split('.');

    if (monthlyPriceParts.length == 1 || monthlyPriceParts.first.length >= 3) {
      return monthlyPriceParts.first;
    }

    var updatedMonthlyPriceLastPart = '';
    const digitAfterCommaCount = 2;

    for (var i = 0; i < digitAfterCommaCount; i++) {
      if (i > monthlyPriceParts.last.length - 1) {
        updatedMonthlyPriceLastPart += '0';
      } else {
        updatedMonthlyPriceLastPart += monthlyPriceParts.last[i];
      }
    }

    final isDelimiterComma = storeApiPurchaseItem.localizedStorePriceWithCurrency.contains(',');

    final delimiter = isDelimiterComma ? ',' : '.';

    return '${monthlyPriceParts.first}$delimiter$updatedMonthlyPriceLastPart';
  }
}
